package com.bysj.studentsystem.filter;

import com.bysj.studentsystem.domain.LoginUser;
import com.bysj.studentsystem.util.JwtUtil;
import com.bysj.studentsystem.util.RedisCacheUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @ClassName JwtAuthenticationTokenFilter
 * @Description:
 * @Author:
 * @Date: 2024/3/10 17:01
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String authorization = request.getHeader("Authorization");
        if (!StringUtils.hasText(authorization)){
            // 放行
            filterChain.doFilter(request, response);
            return;
        }
        // 用户ID
        String userId;
        // 解析token
        try {
            Claims claims = JwtUtil.parseJWT(authorization);
            userId = claims.getSubject();
        } catch (Exception e){
            e.printStackTrace();
            resolver.resolveException(request, response, null, new RuntimeException("token非法"));
            return;
        }
        // 从redis中获取用户信息
        LoginUser loginUser = redisCacheUtil.getCacheObject("login:"+userId);
        if (Objects.isNull(loginUser)){
            resolver.resolveException(request, response, null, new RuntimeException("用户未登录"));
            return;
        }
        // 存入SecurityContextHolder
        // 获取权限信息封装到 AuthenticationToken 中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);

    }
}
